package com.eightywork.life.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

import com.eightywork.life.R;
import com.eightywork.life.activity.PostActivity;
import com.eightywork.life.adapter.GroupMessageListAdapter;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.imageCache.ImageLoader.onLoadingFinishListener;
import com.eightywork.life.model.Community;
import com.eightywork.life.model.Mtalks;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.RTPullListView;
import com.eightywork.life.widget.RTPullListView.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.AbsListView.OnScrollListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ImageView;

public class GroupActivity extends BaseActivity implements OnClickListener {
	private ImageButton menuButton, postButton, joinButton;
	private ImageView headBg;
	private RTPullListView listView;
	private GroupMessageListAdapter adapter;
	public static List<Community> list = new ArrayList<Community>();
	private LayoutInflater inflater;
	private String tagid, name;
	private int page, ismember;
	private AsyncTask task, join;
	private Dialog dialog;
	private ViewGroup footView;
	private boolean isLoading, isRefresh;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group);
		initView();
		initData();
	}
	
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}


	@Override
	protected void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		if (join != null) {
			join.cancel(true);
		}
		super.onDestroy();
	}

	private void initView() {
		menuButton = (ImageButton) findViewById(R.id.button_left);
		menuButton.setOnClickListener(this);
		postButton = (ImageButton) findViewById(R.id.button_right);
		postButton.setOnClickListener(this);
		adapter = new GroupMessageListAdapter(context, list);
		listView = (RTPullListView) findViewById(R.id.listView1);
		footView = (ViewGroup) getLayoutInflater().inflate(
				R.layout.item_footer, null);
		listView.setAdapter(adapter);
		joinButton = (ImageButton) listView.getHeaderView().findViewById(
				R.id.button_join);
		joinButton.setOnClickListener(this);
		View headerView = listView.getHeaderView();
		headBg = (ImageView) headerView.findViewById(R.id.header_bg);
		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) headBg
				.getLayoutParams();
		params.height = getWindowManager().getDefaultDisplay().getHeight() / 3;
		headBg.setLayoutParams(params);
	}

	private void initData() {
		tagid = getIntent().getStringExtra("id");
		name = getIntent().getStringExtra("name");
		ismember = getIntent().getIntExtra("ismember", 0);
		initHeader(name);
		joinButton.setSelected(ismember == 0 ? false : true);
		listView.setonRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if (!isLoading) {
					page = 0;
					isRefresh = true;
					getList();
				}
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == (view.getCount() - 1)
							&& !isLoading) {
						getList();
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

			}
		});
		listView.goLoading();
	}

	public void getList() {
		task = new ListTask().execute();
	}

	class ListTask extends AsyncTask<Void, Void, Mtalks> {
		Mtalks mtalks;

		@Override
		protected void onPreExecute() {
			isLoading = true;
			page++;
			if (!isRefresh) {
				listView.addFooterView(footView);
			}
			super.onPreExecute();
		}

		@Override
		protected Mtalks doInBackground(Void... params) {
			try {
				mtalks = SpaceService.mtalkList(tagid, page + "", "", "");
			} catch (MyHttpException e) {
				showMessage(e.getErrorMessage());
			}
			return mtalks;
		}

		@Override
		protected void onPostExecute(Mtalks result) {
			if (result != null) {
					if (isRefresh) {
						isRefresh = false;
						list.clear();
						listView.onRefreshComplete();
					}else{
						listView.removeFooterView(footView);
					}
					if (mtalks.getList() != null) {
						list.addAll(mtalks.getList());
					}
					if (!mtalks.getPic().equals("") || mtalks.getPic() != null)
						new ImageLoader(context).DisplayImage(mtalks.getPic(), 0, 0,
								headBg, new MyOnLoadFinish(), null, 0);
					adapter.notifyDataSetChanged();
			}	
			isLoading = false;
			super.onPostExecute(result);
		}
	}

	class MyOnLoadFinish implements onLoadingFinishListener {
		@Override
		public void onFinish(Bitmap bitmap, ImageView imageView, List<View> list) {
			if (bitmap == null)
				return;
			float h = bitmap.getHeight();
			float w = bitmap.getWidth();
			LayoutParams params = (LayoutParams) imageView.getLayoutParams();
			params.height = (int) (h / w * imageView.getWidth());
			imageView.setLayoutParams(params);
			imageView.setImageBitmap(bitmap);
		}
	}

	@Override
	public void onClick(View v) {
		if (v == menuButton) {
			finish();
		} else if (v == postButton) {
			Intent intent = new Intent(context, PostActivity.class);
			intent.putExtra("idtype", "mtalkid");
			intent.putExtra("tagid", tagid);
			startActivity(intent);
		} else if (v == joinButton) {
			String tips = "加入" + name + "吗？";
			if (joinButton.isSelected())
				tips = "退出" + name + "吗？";
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setTitle(tips);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							join = new JoinTask().execute();
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog = builder.show();
		}
	}

	class JoinTask extends AsyncTask<Void, Void, JSONObject> {
		@Override
		protected void onPreExecute() {
			showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected JSONObject doInBackground(Void... arg0) {
			try {
				if (joinButton.isSelected())
					return CpService.mtagout(tagid);
				else
					return CpService.mtagjoin(tagid);
			} catch (MyHttpException e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			hideProgressDialog();
			dialog.dismiss();
			if (result != null) {
				if (result.optJSONObject("data").optInt("success") == 1) {
					if (joinButton.isSelected()) {
						joinButton.setSelected(false);
					} else {
						joinButton.setSelected(true);
					}
				}
				showMessage(result.optString("msg"));
			}
			super.onPostExecute(result);
		}
	}
}
